package com.iogogogo.supervisord4j.base.handler;

import com.iogogogo.supervisord.base.BaseResult;
import com.iogogogo.supervisord.exception.SupervisordException;
import com.iogogogo.supervisord4j.base.ResultCode;
import com.iogogogo.supervisord4j.base.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by tao.zeng on 2022/1/5.
 */
@ResponseBody
@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler implements BaseResult {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler({Exception.class})
    public Object exceptionHandler(Exception exception) {
        LOGGER.error(exception.getMessage(), exception);

        if (exception instanceof BaseException) {
            BaseException ex = (BaseException) exception;
            return this.result(ex.getCode(), ex.getMessage());
        }
        return this.result(ResultCode.UNKNOWN.getCode(), exception.getMessage());
    }

    @ExceptionHandler(SupervisordException.class)
    public Object supervisordException(SupervisordException exception) {
        LOGGER.error(exception.getMessage(), exception);

        return this.result(exception.getCode(), exception.getMessage());
    }
}
